package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.CombDetailResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.RealtimeCombineQryResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.RealtimeQryResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.CombDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.InterestDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.RealtimeCombineQryForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.RealtimeQryForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.status.CloseStatus;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.dynamic.DynamicBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.dynamic.back.CombRealtimeQryData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.dynamic.back.DynamicListBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.dynamic.back.DynamicListData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.dynamic.vo.DynamicQueryForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.UserEntity;
import com.cloudbroker.bcs.platform.ltb.middle.entity.ViewpointMsg;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.service.UserService;
import com.cloudbroker.bcs.platform.ltb.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.ltb.middle.thread.FuncThread;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;

/**
 * Created by zhaosh19213 on 2016/9/22.
 */
@Service
public class DynamicBizBizServiceImpl implements DynamicBizService {

    @Resource
    private ViewpointMsgService viewpointMsgService;

    @Resource
    private LightinvestingService lightinvestingService;

    @Resource
    private UserService userService;

    public DynamicListBackVo funcQueryDynamic(DynamicQueryForm form){
        DynamicListBackVo dynamicListBackVo = new DynamicListBackVo();
        List<DynamicListData> dydatalist = new ArrayList<>();
        ViewpointMsg viewpointMsg = new ViewpointMsg();
        viewpointMsg.setClose_status(CloseStatus.NORMAL.getVal());
        Pagination page = new Pagination();
        page.setPage_size(form.getRequest_num());
        List<ViewpointMsg> viewpointMsgList = viewpointMsgService.queryWithPagination(viewpointMsg,page);

        //获取组合交易
        List<CombRealtimeQryData> realtimeQryResultList = getRealtimeTransaction(form);
        //合并2个list
        JSONArray jsonArray = mergeDynamicList(viewpointMsgList, realtimeQryResultList);
        jsonArray = setLeaderInfo(jsonArray,form.getUser_token());
        for (Object object: jsonArray) {
            JSONObject jsonObject = (JSONObject) JSON.toJSON(object);
            DynamicListData dydata = new DynamicListData();
            dydata.setDynamic_type(jsonObject.getString("dynamic_type"));
            dydata.setItem_data(jsonObject.toJSONString());
            dydatalist.add(dydata);
        }
        if (form.getRequest_num()<dydatalist.size()) {
            dydatalist = dydatalist.subList(0, form.getRequest_num());
        }
        dynamicListBackVo.setData_list(dydatalist);
        return VOUtil.setSuccessResult(dynamicListBackVo);
    }

//    public static void main(String[] args) {
//        DynamicListBackVo dynamicListBackVo = new DynamicListBackVo();
//        List list = new ArrayList();
//        ViewpointMsg viewpointMsg = new ViewpointMsg();
//        DynamicListData dynamicListData = new DynamicListData();
//        list.add(viewpointMsg);
//        list.add(dynamicListData);
//
//        dynamicListBackVo.setData_list(list);
//        System.out.println(JSON.toJSON(dynamicListBackVo));
//
//    }

    //加入投顾信息,并添加动态类型
    private JSONArray setLeaderInfo(JSONArray jsonArray,String user_token) {
        JSONArray jsonArray1 =  new JSONArray();
        //投顾信息的缓存，减少数据库读取
        Map<String, String[]> leaderInfoMap = new HashMap<>();
        for (Object object : jsonArray){

            JSONObject jsonObject = (JSONObject) JSON.toJSON(object);
            //设置动态类型
            if (object.getClass().equals(ViewpointMsg.class)) {
                jsonObject.put("dynamic_type", "1");
            } else if (object.getClass().equals(CombRealtimeQryData.class)){
                jsonObject.put("dynamic_type", "2");
            }
            //添加投顾信息（优先从缓存map中获取）
            String leader_user_id = String.valueOf(jsonObject.get("user_id"));
            if (leaderInfoMap.containsKey(leader_user_id)) {
                jsonObject.put("leader_name",leaderInfoMap.get(leader_user_id)[0]);
                jsonObject.put("leader_avatar", leaderInfoMap.get(leader_user_id)[1]);
                jsonObject.put("adviser_type", leaderInfoMap.get(leader_user_id)[2]);
            }else {
                //缓存中不存在则获取
                UserEntity userEntity = userService.get(leader_user_id);
                jsonObject.put("leader_name",userEntity.getAlias_name());
                jsonObject.put("leader_avatar",userEntity.getAvatar()==null?"":userEntity.getAvatar());
                //添加到投顾缓存
                //获取投顾类型
                InterestDetailForm interestDetailForm = new InterestDetailForm();
                interestDetailForm.setUser_token(user_token);
                interestDetailForm.setUser_id(leader_user_id);
                interestDetailForm.setSendercomp_id(userEntity.getSendercomp_id());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(interestDetailForm);
                jsonObject.put("adviser_type",interestDetailVo.getAdviser_type());
                //添加到投顾缓存
                String[] leaderInfo = {userEntity.getAlias_name(), userEntity.getAvatar()==null?"":userEntity.getAvatar(),interestDetailVo.getAdviser_type()};
                leaderInfoMap.put(leader_user_id, leaderInfo);
            }
            jsonArray1.add(jsonObject);
        }
        return jsonArray1;
    }

    private List<CombRealtimeQryData> getRealtimeTransaction(DynamicQueryForm dynamicQueryForm) {
        RealtimeCombineQryForm form = new RealtimeCombineQryForm();
        form.setCompany_id(dynamicQueryForm.getCompany_id());
        form.setSendercomp_id(dynamicQueryForm.getSendercomp_id());
        form.setOp_branch_no(dynamicQueryForm.getOp_branch_no());
        form.setOp_station(dynamicQueryForm.getOp_station());
        form.setOp_entrust_way(dynamicQueryForm.getOp_entrust_way());
        form.setBranch_no(dynamicQueryForm.getBranch_no());
        form.setUser_token(dynamicQueryForm.getUser_token());
        RealtimeCombineQryBackVo realtimeCombineQryBackVo =lightinvestingService.func_realtime_combine_qry(form);
        
        List<RealtimeCombineQryResult> realtimeCombineQryResults = realtimeCombineQryBackVo.getData_list();
        
        if (realtimeCombineQryResults !=null && realtimeCombineQryResults.size() > 0 ){
            List<CombDetailQryBackVo> combDetailQryBackVos = getCombinfo(realtimeCombineQryResults,dynamicQueryForm);

            List<CombRealtimeQryData> combRealtimeQryList = getRealtimeQry(combDetailQryBackVos,dynamicQueryForm);
            return combRealtimeQryList;
        } else {
            return Collections.EMPTY_LIST;
        }
    }

    /**
     * 查询当日发生交易的组合
     * @param realtimeCombineQryResults
     * @param dynamicQueryForm
     * @return
     */
    private List<CombDetailQryBackVo> getCombinfo(List<RealtimeCombineQryResult> realtimeCombineQryResults,
                             final DynamicQueryForm dynamicQueryForm){
        List<Callable> tasks = new ArrayList();
        for (final RealtimeCombineQryResult result:realtimeCombineQryResults) {
            tasks.add(
                    new Callable<Object>() {
                        public Object call() throws Exception {
                            CombDetailForm combDetailForm = new CombDetailForm();
                            combDetailForm.setSendercomp_id(dynamicQueryForm.getSendercomp_id());
                            combDetailForm.setOp_branch_no(dynamicQueryForm.getOp_branch_no());
                            combDetailForm.setOp_station(dynamicQueryForm.getOp_station());
                            combDetailForm.setOp_entrust_way(dynamicQueryForm.getOp_entrust_way());
                            combDetailForm.setBranch_no(dynamicQueryForm.getBranch_no());
                            combDetailForm.setCombi_code(result.getCombi_code());
                            combDetailForm.setUser_token(dynamicQueryForm.getUser_token());
                            return lightinvestingService.func_comb_details(combDetailForm);
                        }
                    }
            );
        }
        List<CombDetailQryBackVo> obj = FuncThread.submit(tasks);
        List<CombDetailQryBackVo> result = new ArrayList<>();
        for (CombDetailQryBackVo combDetailQryBackVo: obj) {
            if (combDetailQryBackVo.getData_list()!=null && combDetailQryBackVo.getData_list().size()>0) {
                CombDetailResult combDetailResult = combDetailQryBackVo.getData_list().get(0);
                InterestDetailForm interestDetailForm = new InterestDetailForm();
                interestDetailForm.setUser_token(dynamicQueryForm.getUser_token());
                interestDetailForm.setUser_id(combDetailResult.getUser_id());
                interestDetailForm.setSendercomp_id(dynamicQueryForm.getSendercomp_id());
                InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(interestDetailForm);
                if (!interestDetailVo.getAdviser_type().equals("2")){
                    result.add(combDetailQryBackVo);
                }
            }
        }
        return result;
    }

    /**
     * 根据当日发生交易的组合列表查询所有的交易
     * @param combDetailQryBackVo
     * @param dynamicQueryForm
     * @return
     */
    private List<CombRealtimeQryData> getRealtimeQry(final List<CombDetailQryBackVo> combDetailQryBackVo,
                                                   final DynamicQueryForm dynamicQueryForm) {
        List<Callable> tasks = new ArrayList();
        //userId 列表
        final List<String> businAccounts = new ArrayList<>();
        //用组合的业务资金账号向后台请求交易记录
        for (final CombDetailQryBackVo result : combDetailQryBackVo) {

            tasks.add(
                    new Callable<Object>() {
                        public Object call() throws Exception {
                            RealtimeQryForm realtimeQryForm = new RealtimeQryForm();
                            if (result.getData_list() != null && result.getData_list().size() > 0) {
                                CombDetailResult combDetailResult = result.getData_list().get(0);
                                //busin_account去重
                                if(businAccounts.contains(combDetailResult.getBusin_account())){
                                    return null;
                                }else {
                                    businAccounts.add(combDetailResult.getBusin_account());
                                }
                                realtimeQryForm.setCompany_id(combDetailResult.getCompany_id());
                                realtimeQryForm.setBusiness_no(Long.valueOf(combDetailResult.getBusinsys_no()));
                                realtimeQryForm.setSendercomp_id(dynamicQueryForm.getSendercomp_id());
                                realtimeQryForm.setOp_branch_no(dynamicQueryForm.getOp_branch_no());
                                realtimeQryForm.setOp_station(dynamicQueryForm.getOp_station());
                                realtimeQryForm.setOp_entrust_way(dynamicQueryForm.getOp_entrust_way());
                                realtimeQryForm.setBranch_no(dynamicQueryForm.getBranch_no());
                                realtimeQryForm.setUser_token(dynamicQueryForm.getUser_token());
                                realtimeQryForm.setUser_id(combDetailResult.getUser_id());
                                realtimeQryForm.setBusin_account(combDetailResult.getBusin_account());
                                RealtimeQryBackVo realtimeQryBackVo = lightinvestingService.func_realtime_qry(realtimeQryForm);
                                CombRealtimeQryBackVo comb = new CombRealtimeQryBackVo();
                                comb.setData_list(realtimeQryBackVo.getData_list());
                                comb.setCombi_code(combDetailResult.getCombi_code());
                                comb.setCombi_name(combDetailResult.getCombi_name());
                                return comb;
                            } else {
                                return null;
                            }
                        }
                    }
            );
        }
        List<CombRealtimeQryBackVo> combRealtimeQryBackVo = FuncThread.submit(tasks);
        //将返回的所有结果组合成一个list
        List<CombRealtimeQryData> totalRealtimeResultList = new ArrayList<>();
        for (CombRealtimeQryBackVo back : combRealtimeQryBackVo) {
            if (back != null && back.getData_list() != null && back.getData_list().size() > 0) {
                for (RealtimeQryResult realtimeQryResult : back.getData_list()) {
                    //过滤非正常交易
                    if (realtimeQryResult!=null &&
                            realtimeQryResult.getReal_status()!=null &&
                            realtimeQryResult.getReal_status().equals("0")){
                        CombRealtimeQryData data = new CombRealtimeQryData();
                        data.setBusiness_amount(realtimeQryResult.getBusiness_amount());
                        data.setCurr_time(realtimeQryResult.getCurr_time());
                        //将后台时间拼装转换成时间戳
                        data.setBusiness_time(Long.parseLong(transTime(realtimeQryResult.getInit_date().toString(),realtimeQryResult.getBusiness_time().toString())));
                        data.setBusiness_price(realtimeQryResult.getBusiness_price());
                        data.setBusiness_balance(realtimeQryResult.getBusiness_balance());
                        data.setStock_name(realtimeQryResult.getStock_name());
                        data.setUser_id(realtimeQryResult.getUser_id());
                        data.setInit_date(realtimeQryResult.getInit_date());
                        data.setEntrust_bs(realtimeQryResult.getEntrust_bs());
                        data.setProd_code(realtimeQryResult.getProd_code());
                        data.setCombi_code(back.getCombi_code());
                        data.setCombi_name(back.getCombi_name());
                        if (!totalRealtimeResultList.contains(data)) {
                            totalRealtimeResultList.add(data);
                        }
                    }
                }
            }
        }
        return totalRealtimeResultList;
    }

    private String transTime(String init_date,String business_time){
        SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmss");
        //5位数的时间需要转化成6位
        if (business_time.length()==5){
            business_time = "0" + business_time;
        }
        Date d = null;
        try {
            d = format.parse(init_date + business_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return String.valueOf(d.getTime());
    }

    private JSONArray mergeDynamicList(List<ViewpointMsg> viewpointMsgList,
                                       List<CombRealtimeQryData> realtimeQryResultList){
        //先将后台的交易动态进行排序
        Collections.sort(realtimeQryResultList, new Comparator<CombRealtimeQryData>() {
            public int compare(CombRealtimeQryData arg0, CombRealtimeQryData arg1) {
                return arg0.getBusiness_time().compareTo(arg1.getBusiness_time());
            }
        });
        Collections.reverse(realtimeQryResultList);
        JSONArray jsonArray = new JSONArray();
        int i=0,j=0;
        while (i<viewpointMsgList.size() && j<realtimeQryResultList.size()){
            if (viewpointMsgList.get(i).getSend_time() >
                    Long.valueOf(realtimeQryResultList.get(j).getBusiness_time())){
                jsonArray.add(viewpointMsgList.get(i));
                i++;
            }else{
                jsonArray.add(realtimeQryResultList.get(j));
                j++;
            }
        }

        while (i<viewpointMsgList.size()){
            jsonArray.add(viewpointMsgList.get(i));
            i++;
        }

        while (j<realtimeQryResultList.size()){
            jsonArray.add(realtimeQryResultList.get(j));
            j++;
        }
        return jsonArray;
    }
}
